package cs4game;




import org.lwjgl.opengl.GL11;
import org.newdawn.slick.opengl.Texture;

public abstract class MobEntity extends Entity{
	float width, height, depth, prevHeight;
	Texture tex;
	double[][][][] texture;
	protected float[] velocity, acceleration;
	protected boolean visible = true;
	//protected float[] velocity;

	public MobEntity(){

	}

	public MobEntity(World w){
		world = w;
		velocity = new float[]{0,0,0}; 
		acceleration = new float[]{0,.05f,0}; 
		//prevHeight = pos.y;
	}
	
	public MobEntity(Vector3D p, World w){
		this(w);
		pos = p;
		defineTexture();
		width = height = depth = 0.6f;
		box = new BoundingBox(-1*width/2, width/2, -1*height/2, height/2, -1*depth/2, depth/2);
		prevHeight = p.y;
	}
	
	protected abstract void defineTexture();

	public void draw(){
		if(visible){
			GL11.glBegin(GL11.GL_QUADS);
			if(texture.length>0)
				for(int i = 0; i< texture[0].length; i++){
					for(int j = 0; j< texture[0][i].length; j++){
						//GL11.glNormal3f(n[i][0], n[i][1], n[i][2]);
						GL11.glTexCoord2d(texture[0][i][j][0], texture[0][i][j][1]);
						GL11.glVertex3d(texture[1][i][j][0]+pos.x, texture[1][i][j][1]+pos.y, texture[1][i][j][2]+pos.z);
					}

				}
			GL11.glEnd();
		}
	}


	public void move(float time){
		if(velocity[0]!=0){
			pos.x+=velocity[0]*(float)((time)/(1000.0/60.0));
			if(collideWithTerrain(time)){
				pos.x-=velocity[0]*(float)((time)/(1000.0/60.0));
			}
		}
		prevHeight = pos.y;
		if(velocity[1]!=0){
			pos.y+=velocity[1]*(float)((time)/(1000.0/60.0));
			if(collideWithTerrain(time)){
				pos.y-=velocity[1]*(float)((time)/(1000.0/60.0));
			}
		}
		if(velocity[2]!=0){
			pos.z+=velocity[2]*(float)((time)/(1000.0/60.0));
			if(collideWithTerrain(time)){
				pos.z-=velocity[2]*(float)((time)/(1000.0/60.0));
			}
		}
		
		if(pos.y <= -2){
			velocity[1]+=acceleration[1];
		}else{
			velocity[1] = 0;
		}
		for(Vector3D vec: world.allBlocks.keySet()){
			if((pos.x-.3f < vec.x+.5 && pos.x-.3f > vec.x-.5) || (pos.x+.3f > vec.x-.5 && pos.x+.3f < vec.x-.5)){
				if((pos.z-.3f < vec.z+.5 && pos.z-.3f > vec.z-.5) || (pos.z+.3f > vec.z-.5 && pos.z+.3f < vec.z-.5)){
					if(vec.y < pos.y && vec.y > prevHeight){
						pos.y = prevHeight;
					}
				}	
			}
		}
	}

	public boolean collideWithTerrain(float time){
		boolean collided = false;
		box = new BoundingBox(-1*width/2, width/2, -1*height/2, height/2, -1*depth/2, depth/2);
		box = shiftedBoundingBox();
		for(Vector3D p: world.allBlocks.keySet()){

			int id = world.allBlocks.get(p);
			BlockID def = BlockDefs.get(getID(id));

			if(def.getBoundingBox(p, id).intersects(box)){
				//System.out.println("("+pos.x+", "+pos.z+")");
				box = shiftedBoundingBox();
				return true;
			}

		}
		return collided;
	}

	public int getID(int block){return (block & 0xFFF00000)>>52;}

	

	public void setVelocity(float[] fs) {
		velocity = fs;		
	}
	
	

}
